package org.example;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;

/**
 * 2024-3-20 早上面试被问到HashMap的put方法内部是如何实现的，我没有回答得上来。这里学习一下
 */
public class Main {
    public static void main(String[] args) {
        int MAXIMUM_CAPACITY = 1 << 30;
        // Map<String, String> map = new HashMap<>(MAXIMUM_CAPACITY + 1);
        Map<String, String> map = new TreeMap<>(new Comparator<String>() {
            @Override
            public int compare(String o1, String o2) {
                if(o1 == null && o2 != null){
                    return -1;
                }
                if(o1 == null && o2 == null){
                    return 0;
                }
                if(o2 == null && o1 != null){
                    return -1;
                }
                return o1.compareTo(o2);
            }
        });
        map.put("key", "value");
        map.put(null, "the value of null");
        map.put(null, "2222222222l");
        System.out.println("value of null:" + map.get(null));

        int a = Integer.MAX_VALUE -2;
        int b = 4;
        if( a + b > Integer.MAX_VALUE){
            System.out.println("true");
        }else {
            System.out.println("false");
        }
        testInitialTableSize();
    }


    static void testInitialTableSize(){
        System.out.println(tableSizeFor( 1));// 1
        System.out.println(tableSizeFor( 2));// 2
        System.out.println(tableSizeFor( 3));// 4
        System.out.println(tableSizeFor( 4));// 4
        System.out.println(tableSizeFor( 5));// 8
        System.out.println(tableSizeFor( 6));// 8
        System.out.println(tableSizeFor( 7));// 8
        System.out.println(tableSizeFor( 8));// 8
        System.out.println(tableSizeFor( 9)); // 16
        System.out.println(tableSizeFor( 10));// 16
    }

    static final int tableSizeFor(int cap) {
        final int MAXIMUM_CAPACITY = 1 << 30;
        int n = -1 >>> Integer.numberOfLeadingZeros(cap - 1);
        return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;
    }
}